package net.sudot.chess.business.dao;

import net.sudot.chess.business.dto.ChatMessageDTO;
import net.sudot.chess.business.model.ChatRecord;
import org.springframework.stereotype.Repository;

import javax.persistence.TypedQuery;
import java.time.Instant;
import java.util.List;

/**
 * 游戏
 *
 * @author tangjialin on 2018-02-27.
 */
@Repository
public class ChatRecordDao extends BaseDao<ChatRecord> {
    /**
     * 获取房间下所有聊天信息
     *
     * @param roomId 房间主键
     * @return 返回聊天信息
     */
    public List<ChatRecord> findByRoom(Long roomId) {
        String ql = "SELECT chatRecord FROM ChatRecord chatRecord WHERE chatRecord.roomId = :roomId ORDER BY chatRecord.createdDate ASC";
        TypedQuery<ChatRecord> query = entityManager.createQuery(ql, entityClass);
        query.setParameter("roomId", roomId);
        return query.getResultList();
    }

    /**
     * 获取房间下指定时间后的聊天信息
     *
     * @param roomId    房间主键
     * @param startDate 指定的起始时间
     * @return 返回聊天信息
     */
    public List<ChatMessageDTO> findListByRoomAtAfter(Long roomId, Instant startDate) {
        String ql = "SELECT new net.sudot.chess.business.dto.ChatMessageDTO(" +
                " chatRecord.content," +
                " customer.id AS customerId," +
                " customer.nickname," +
                " customer.head)" +
                " FROM ChatRecord chatRecord" +
                " INNER JOIN Customer customer ON customer.id = chatRecord.createdBy" +
                " WHERE chatRecord.roomId = :roomId" +
                " AND chatRecord.createdDate >= :startDate" +
                " ORDER BY chatRecord.createdDate ASC";
        TypedQuery<ChatMessageDTO> query = entityManager.createQuery(ql, ChatMessageDTO.class);
        query.setParameter("roomId", roomId);
        query.setParameter("startDate", startDate);
        return query.getResultList();
    }
}
